package client

import (
	"fmt"
	"net"
	"tio-proxy-agent/log"
)

type BsPacket struct {
	Type byte
	Body []byte
}

func (packet *BsPacket) GetType() byte {
	return packet.Type
}

func (packet *BsPacket) GetBody() []byte {
	return packet.Body
}

type ConnectSuccessBody struct {
	Token    string `json:"token"`
	Host     string `json:"host"`
	Protocol string `json:"protocol"`
	BsId     string `json:"bsId"`
}

func (body *ConnectSuccessBody) Handler() {
	log.SugarLogger.Info("当前通道协议:", body.Protocol)
	log.SugarLogger.Info("访问域名地址:", body.Host)
}

type TcpBody struct {
	Bytes    []byte `json:"bytes"`
	BsId     string `json:"bsId"`
	Protocol string `json:"protocol"`
}

func (body *TcpBody) Handler() {
	packet := &BsPacket{
		Type: 98,
		Body: body.Bytes,
	}
	ChannelManage[body.BsId].SendData <- packet
}

type TcpTunnelBody struct {
	BsId     string `json:"bsId"`
	Protocol string `json:"protocol"`
}

func (body *TcpTunnelBody) Handler() {

	if ChannelManage[body.BsId] == nil {
		if body.Protocol == "http" {
			config := new(GioClientForwardConfig)
			config.BsId = body.BsId
			gioClientForward := NewGioClientForward(config, nil, body.BsId)
			go func() {
				gioClientForward.Connect(TunnelInfo.TargetHost, TunnelInfo.TargetPort)
			}()
			<-gioClientForward.isInitOk
		} else {
			config := new(GioClientTcpForwardConfig)
			config.BsId = body.BsId
			gioClientForward := NewGioClientForward(config, nil, body.BsId)
			go func() {
				gioClientForward.Connect(TunnelInfo.TargetHost, TunnelInfo.TargetPort)
			}()
			<-gioClientForward.isInitOk
		}
	}
}

type TcpCloseTunnelBody struct {
	BsId     string `json:"bsId"`
	Protocol string `json:"protocol"`
}

func (body *TcpCloseTunnelBody) Handler() {
	bsId := body.BsId
	ctx := ChannelManage[bsId]
	if ctx != nil {
		item, err := ctx.Get("conn")
		if err != nil {
			fmt.Println("err:", err)
		}
		var conn = item.(net.Conn)
		err = conn.Close()
		if err != nil {
			fmt.Println("err:", err)
		}
		delete(ChannelManage, bsId)
	}
}
